package com.robot.command;

import iqq.im.QQException;
import iqq.im.actor.QQActor;
import iqq.im.bean.QQGroupMember;
import iqq.im.bean.QQMsg;
import iqq.im.bean.QQUser;
import iqq.im.core.QQModule;
import iqq.im.module.UserModule;

import java.lang.reflect.Constructor;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.robot.core.Context;
import com.robot.ui.MainFrame;
import com.robot.ui.QQFrame;

public class MsgDispatcher implements Runnable{
	private BlockingQueue<QQMsg> msgQueue;
	private Thread dispatchThread;
	private Context context;
	public MsgDispatcher(Context context){
		this.context = context;
		this.msgQueue = new LinkedBlockingQueue<QQMsg>();
		this.dispatchThread = new Thread(this);
		this.dispatchThread.start();
	}	
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 * 处理被动事件，如：
	 * 记录发主记录次数，欢迎新人
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void run() {
		
		while(true){
			try {
				QQMsg msg = msgQueue.take();
				//找QQ
				if(msg.getFrom().getQQ()==0){
					UserModule userModule = context.getModule(QQModule.Type.USER);
					userModule.getUserAccount(msg.getFrom(),null).waitFinalEvent();
				}	
				msg = wrapMsg(msg);
				//pattern reg
				Pattern	pattern = Pattern.compile("[#＃]([a-zA-Z?？]{1,4}) *([^ ]*) ?([^ ]*) ?([^ ]*)");
				Matcher	matcher = pattern.matcher(msg.getText());
				if(matcher.find()){			
					for(String key:context.getConfig().getConfigMap().keySet()){				
						if(matcher.group(1).equalsIgnoreCase(context.getConfig().get(key))){
							Class clazz = Class.forName(key);
							Constructor constructor = clazz.getConstructor(Context.class,QQMsg.class);
							context.pushActor((QQActor) constructor.newInstance(context,msg));
						}
					}
				}
				// is autoReply
				if("开".equals(context.getConfig().get("自动回复"))){
					context.pushActor(new AutoReplyActor(context,msg));			
				}
				//CYJL
				if("开".equals(context.getConfig().get("成语接龙"))
						&&msg.getText().trim().length()==4){
					context.pushActor(new CYJLActor(context,msg));	
				}
			} catch (Exception e) {
				System.err.println(e.getMessage());
			}
		}
	}
	public QQMsg wrapMsg(QQMsg msg) throws QQException{		
		QQUser user = msg.getFrom();
		StringBuffer displayUI = new StringBuffer();
		if(msg.getType()==QQMsg.Type.GROUP_MSG){
			String cardName = ((QQGroupMember)user).getCard();
			if (cardName != null && !"".equals(cardName)) {
				msg.getFrom().setNickname(cardName);
			}
			displayUI.append(" [群消息] ");			
		}else if(msg.getType()==QQMsg.Type.SESSION_MSG){
			displayUI.append(" [临时会话] ");			
		}else if(msg.getType()==QQMsg.Type.BUDDY_MSG){
			displayUI.append("　[好友消息] ");	
		}
		displayUI.insert(0,user.getNickname()+"("+user.getQQ()+"):"+msg.getText());
		displayUI.append(" "+format(msg.getDate()));		
		((MainFrame) context.getFrame(QQFrame.Type.MAIN))
			.showMsg(displayUI.toString(),msg.getFontColor());
		
		return msg;
	}
	
	/**
	 * 时间格式
	 * */
	private DateFormat fmt = new SimpleDateFormat("HH:mm:ss");
	public String format (Date date){
		return fmt.format(date);
	}
	/**
	 * pushMsg进等待队列
	 */
	public void pushMsg(QQMsg msg) {
		this.msgQueue.add(msg);		
	}
}
